import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { Form, Input, Select, Switch, InputNumber, TreeSelect, DatePicker, TimePicker, Checkbox, Radio, Cascader, Modal } from 'antd';
import type { FormInstance, FormProps } from 'antd';
import type { FormFieldConfig, FormSectionConfig, FormConfig, DynamicFormProps, DynamicFormRef } from '@/types/dynamic-form';
import dayjs from 'dayjs';
import IconSelect from '@/components/common/IconSelect';

const { Item: FormItem } = Form;
const { Option } = Select;
const { TextArea } = Input;
const { Group: CheckboxGroup } = Checkbox;
const { Group: RadioGroup } = Radio;
const { RangePicker: DateRangePicker } = DatePicker;
const { RangePicker: TimeRangePicker } = TimePicker;

const DynamicFormComponent: React.FC<DynamicFormProps> = forwardRef<DynamicFormRef, DynamicFormProps>(({
  config,
  values,
  visible,
  loading = false,
  width = 800,
  centered = true,
  closable = true,
  maskClosable = false,
  keyboard = true,
  destroyOnClose = true,
  forceRender = false,
  afterClose,
  onOk,
  onCancel,
  onSubmit,
  onValuesChange,
  customFields = {},
  className,
  style,
  modal = true,
}, ref) => {
  const [form] = Form.useForm();
  const formRef = useRef<FormInstance>(form);
  const [internalVisible, setInternalVisible] = React.useState(visible || false);

  useEffect(() => {
    setInternalVisible(!!visible);
  }, [visible]);

  useEffect(() => {
    if (internalVisible && values) {
      const formattedValues = { ...values };
      form.setFieldsValue(formattedValues);
    } else if (internalVisible && config.initialValues) {
      const formattedValues = { ...config.initialValues };
      form.setFieldsValue(formattedValues);
    } else if (internalVisible) {
      form.resetFields();
    }
  }, [internalVisible, values, config.initialValues, form]);

  useImperativeHandle(ref, () => ({
    form,
    submit: async () => {
      try {
        const values = await form.validateFields();
        return values;
      } catch (error) {
        throw error;
      }
    },
    resetFields: (fields) => form.resetFields(fields),
    setFieldsValue: (values) => form.setFieldsValue(values),
    getFieldsValue: (fieldNames) => form.getFieldsValue(fieldNames),
    getFieldValue: (fieldName) => form.getFieldValue(fieldName),
    validateFields: (fieldNames) => form.validateFields(fieldNames),
    validateFieldsError: (fieldNames) => form.validateFields(fieldNames),
    scrollToField: (fieldName, options) => form.scrollToField(fieldName, options),
    setFields: (fields) => form.setFields(fields),
    getInternalHooks: (key) => form.getInternalHooks(key),
  }));

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (onSubmit) {
        await onSubmit(values);
      }
      if (onOk) {
        onOk();
      }
    } catch (error) {
      // 静默处理表单验证失败
    }
  };

  const handleCancel = () => {
    form.resetFields();
    if (onCancel) {
      onCancel();
    }
  };

  const handleValuesChange = (changedValues: any, allValues: any) => {
    if (config.onValuesChange) {
      config.onValuesChange(changedValues, allValues);
    }
    if (onValuesChange) {
      onValuesChange(changedValues, allValues);
    }
  };

  const renderField = (field: FormFieldConfig, formValues: any) => {
    const CustomComponent = customFields[field.key];

    if (CustomComponent) {
      return <CustomComponent form={form} field={field} values={formValues} />;
    }

    if (field.itemRender) {
      return field.itemRender(formValues[field.key], field);
    }

    if (field.hidden) {
      return null;
    }

    const commonProps = {
      placeholder: field.placeholder || `请输入${field.label}`,
      disabled: field.disabled,
      readOnly: field.readonly,
      allowClear: field.allowClear,
      showSearch: field.showSearch,
      filterOption: field.filterOption,
      ...field.fieldProps,
    };

    switch (field.type) {
      case 'input':
        return <Input {...commonProps} />;

      case 'textarea':
        return <TextArea {...commonProps} rows={4} />;

      case 'select':
        return (
          <Select {...commonProps} mode={field.multiple ? 'multiple' : undefined}>
            {field.options?.map(option => (
              <Option key={option.value} value={option.value} disabled={option.disabled}>
                {option.label}
              </Option>
            ))}
          </Select>
        );

      case 'number':
        return (
          <InputNumber
            {...commonProps}
            min={field.min}
            max={field.max}
            step={field.step}
            precision={field.precision}
            style={{ width: '100%' }}
          />
        );

      case 'switch':
        return (
          <Switch
            checked={formValues[field.key]}
            disabled={field.disabled}
            checkedChildren={field.fieldProps?.checkedChildren || '是'}
            unCheckedChildren={field.fieldProps?.unCheckedChildren || '否'}
          />
        );

      case 'date':
        return (
          <DatePicker
            {...commonProps}
            format={field.format || 'YYYY-MM-DD'}
            showTime={field.showTime}
            style={{ width: '100%' }}
          />
        );

      case 'time':
        return (
          <TimePicker
            {...commonProps}
            format={field.format || 'HH:mm:ss'}
            style={{ width: '100%' }}
          />
        );

      case 'datetime':
        return (
          <DatePicker
            {...commonProps}
            showTime
            format={field.format || 'YYYY-MM-DD HH:mm:ss'}
            style={{ width: '100%' }}
          />
        );

      case 'tree-select':
        return (
          <TreeSelect
            {...commonProps}
            treeData={field.treeData}
            treeDefaultExpandAll
            treeNodeFilterProp="title"
            style={{ width: '100%' }}
          />
        );

      case 'cascader':
        return (
          <Cascader
            {...commonProps}
            options={field.options}
            style={{ width: '100%' }}
          />
        );

      case 'checkbox':
        if (field.options) {
          return (
            <CheckboxGroup
              {...commonProps}
              options={field.options}
              disabled={field.disabled}
            />
          );
        }
        return <Checkbox {...commonProps} />;

      case 'radio':
        if (field.options) {
          return (
            <RadioGroup
              {...commonProps}
              options={field.options}
              disabled={field.disabled}
            />
          );
        }
        return <Radio {...commonProps}>{field.label}</Radio>;

      case 'icon-select':
        return (
          <IconSelect
            value={formValues[field.key] || ''}
            onChange={(value) => {
              form.setFieldsValue({ [field.key]: value });
              if (config.onValuesChange) {
                config.onValuesChange({ [field.key]: value }, form.getFieldsValue());
              }
            }}
            placeholder={field.placeholder || '请选择图标'}
            disabled={field.disabled}
            allowClear={field.allowClear !== false}
            style={{ width: '100%' }}
            size={field.fieldProps?.size}
          />
        );

      default:
        return <Input {...commonProps} />;
    }
  };

  const renderFormItem = (field: FormFieldConfig, formValues: any) => {
    if (field.condition && !field.condition(formValues)) {
      return null;
    }

    const isRequired = typeof field.required === 'function' ? field.required(formValues) : field.required;
    const rules = typeof field.rules === 'function' ? field.rules(formValues) : field.rules;
    const formItemProps = {
      name: field.key,
      label: field.label,
      rules: rules || (isRequired ? [{ required: true, message: `请输入${field.label}` }] : []),
      tooltip: field.tooltip,
      extra: field.extra,
      dependencies: field.dependencies,
      shouldUpdate: field.shouldUpdate,
      normalize: field.normalize,
      getValueFromEvent: field.getValueFromEvent,
      hidden: field.hidden,
      ...field.formItemProps,
    };

    return (
      <FormItem key={field.key} {...formItemProps}>
        {renderField(field, formValues)}
      </FormItem>
    );
  };

  const renderDynamicField = (field: FormFieldConfig) => {
    return (
      <Form.Item shouldUpdate={(prevValues, currentValues) =>
        (field.shouldUpdate && typeof field.shouldUpdate === 'function') ? field.shouldUpdate(prevValues, currentValues) : false
      }>
        {(form) => {
          const formValues = form.getFieldsValue();
          return renderFormItem(field, formValues);
        }}
      </Form.Item>
    );
  };

  const renderSection = (section: FormSectionConfig, formValues: any) => {
    // 处理section级别的条件显示
    if (section.condition && !section.condition(formValues)) {
      return null;
    }

    const sectionStyle: React.CSSProperties = {
      marginBottom: section.collapsed ? 0 : 24,
      ...(section.collapsed ? { border: 'none', padding: 0 } : {}),
    };

    // 处理动态字段生成
    let fields = section.fields;
    if (typeof section.fields === 'function') {
      fields = section.fields(formValues);
    }

    // 处理动态列数
    let colCount = section.col || 1;
    if (typeof section.col === 'function') {
      colCount = section.col(formValues);
    }

    // 过滤掉需要隐藏的字段
    const visibleFields = fields.filter((field: any) => {
      if (field.condition && !field.condition(formValues)) {
        return false;
      }
      if (field.hidden) {
        return false;
      }
      return true;
    });

    if (visibleFields.length === 0) {
      return null;
    }

    return (
      <div key={section.key} className="dynamic-form-section" style={sectionStyle}>
        {section.title && (
          <div className="dynamic-form-section-title" style={{ marginBottom: 16, fontSize: 16, fontWeight: 'bold' }}>
            {section.title}
            {section.extra && (
              <span style={{ marginLeft: 8, fontSize: 14, fontWeight: 'normal' }}>
                {section.extra}
              </span>
            )}
          </div>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${colCount}, 1fr)`, gap: section.gutter || 16 }}>
          {visibleFields.map((field: any) =>
            field.shouldUpdate ? renderDynamicField(field) : renderFormItem(field, formValues)
          )}
        </div>
      </div>
    );
  };

  const formContent = (
    <Form
      ref={formRef}
      form={form}
      layout={config.layout || 'vertical'}
      labelAlign={config.labelAlign || 'left'}
      labelCol={config.labelCol ? { span: config.labelCol } : undefined}
      wrapperCol={config.wrapperCol ? { span: config.wrapperCol } : undefined}
      colon={config.colon}
      requiredMark={config.requiredMark}
      scrollToFirstError={config.scrollToFirstError}
      validateMessages={config.validateMessages}
      size={config.size}
      onValuesChange={handleValuesChange}
      onFinish={config.onFinish}
      onFinishFailed={config.onFinishFailed}
      className={className}
      style={style}
    >
      {config.sections.map(section => {
        if (section.shouldUpdate) {
          return (
            <Form.Item shouldUpdate={section.shouldUpdate} key={section.key}>
              {(form) => {
                const formValues = form.getFieldsValue();
                return renderSection(section, formValues);
              }}
            </Form.Item>
          );
        } else {
          return renderSection(section, form.getFieldsValue());
        }
      })}

      {config.actions && (
        <div style={{ marginTop: 24, textAlign: 'right' }}>
          {config.actions}
        </div>
      )}
    </Form>
  );

  if (modal) {
    return (
      <Modal
        title={config.title}
        open={internalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={width}
        centered={centered}
        closable={closable}
        maskClosable={maskClosable}
        keyboard={keyboard}
        destroyOnClose={destroyOnClose}
        forceRender={forceRender}
        afterClose={afterClose}
        confirmLoading={loading}
        okText={config.submitButton?.text || '确定'}
        cancelText={config.cancelButton?.text || '取消'}
      >
        {formContent}
      </Modal>
    );
  }

  return formContent;
});

export default DynamicFormComponent;